import Taro from '@tarojs/taro'

export interface RequestConfig {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: Record<string, string>
  timeout?: number
}

export interface RequestResponse<T = any> {
  code: number
  data: T
  message?: string
}

// 基础配置
const BASE_URL = process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : 'https://api.example.com'
const DEFAULT_TIMEOUT = 10000

// 请求拦截器
const requestInterceptor = (config: RequestConfig) => {
  // 添加通用请求头
  config.header = {
    'Content-Type': 'application/json',
    ...config.header
  }

  // 添加token
  try {
    const token = Taro.getStorageSync('token')
    if (token) {
      config.header.Authorization = `Bearer ${token}`
    }
  } catch (error) {
    console.warn('获取token失败:', error)
  }

  return config
}

// 响应拦截器
const responseInterceptor = (response: any) => {
  const { statusCode, data } = response

  if (statusCode >= 200 && statusCode < 300) {
    return data
  }

  // 处理错误状态码
  let errorMessage = '请求失败'
  switch (statusCode) {
    case 401:
      errorMessage = '未授权，请重新登录'
      // 清除token
      try {
        Taro.removeStorageSync('token')
        Taro.removeStorageSync('user_info')
      } catch (error) {
        console.error('清除存储失败:', error)
      }
      break
    case 403:
      errorMessage = '拒绝访问'
      break
    case 404:
      errorMessage = '请求地址不存在'
      break
    case 500:
      errorMessage = '服务器内部错误'
      break
    default:
      errorMessage = data?.message || `请求失败 (${statusCode})`
  }

  throw new Error(errorMessage)
}

// 通用请求方法
export const request = async <T = any>(config: RequestConfig): Promise<T> => {
  try {
    // 处理URL
    const url = config.url.startsWith('http') ? config.url : `${BASE_URL}${config.url}`
    
    // 应用请求拦截器
    const finalConfig = requestInterceptor({
      ...config,
      url,
      timeout: config.timeout || DEFAULT_TIMEOUT
    })

    // 发起请求
    const response = await Taro.request(finalConfig)
    
    // 应用响应拦截器
    return responseInterceptor(response)
  } catch (error) {
    console.error('请求失败:', error)
    throw error
  }
}

// GET 请求
export const get = <T = any>(url: string, params?: any, config?: Partial<RequestConfig>): Promise<T> => {
  return request<T>({
    url: params ? `${url}?${new URLSearchParams(params).toString()}` : url,
    method: 'GET',
    ...config
  })
}

// POST 请求
export const post = <T = any>(url: string, data?: any, config?: Partial<RequestConfig>): Promise<T> => {
  return request<T>({
    url,
    method: 'POST',
    data,
    ...config
  })
}

// PUT 请求
export const put = <T = any>(url: string, data?: any, config?: Partial<RequestConfig>): Promise<T> => {
  return request<T>({
    url,
    method: 'PUT',
    data,
    ...config
  })
}

// DELETE 请求
export const del = <T = any>(url: string, config?: Partial<RequestConfig>): Promise<T> => {
  return request<T>({
    url,
    method: 'DELETE',
    ...config
  })
} 